String Functions and Manipulation in C++
String Functions are operations provided by the
1. strlen()
The strlen() function in C++ is used to find the length of a null-terminated string. It is part of the
Example of strlen() function:
#include <string>
// Main function
int main() {
std::string cppString = "Hello, World!";
// Using length() or size() to find the length of the C++ string
size_t length = cppString.length();
std::cout << "Length of the string: " << length << "\n";
return 0;
}
Keep in mind that the length does not include the null terminator '\0', and it represents the number of characters in the string before the null terminator.
2. strcpy()
The strcpy() function in C++ is used to copy the contents of one string to another. It is part of the
Example of strcpy() function:
#include <cstring>
// Main function
int main() {
// Source C-style string
const char source[] = "Hello, World!";
// Allocate memory for the destination string (plus one for the null terminator)
char destination[20]; // Make sure it's large enough to hold the source string
// Using strcpy to copy the contents of the source string to the destination string
std::strcpy(destination, source);
// Print the result
std::cout << "Source string: " << source << "\n";
std::cout << "Destination string: " << destination << "\n";
return 0;
}
Remember, if the destination space isn't big enough for both the source string and the null terminator, it might cause a buffer overflow, leading to unpredictable issues.
3. strcat()
The strcat() function in C++ is used to concatenate (append) the content of one string to the end of another string. It is part of the
Example of strlcat() function:
#include <cstring>
// Main function
int main() {
// Declare and initialize destination and source strings
char destination[20] = "Hello, ";
const char source[] = "World!";
// Using strcat to concatenate the content of the source string to the destination string
std::strcat(destination, source);
// Print the result
std::cout << "Concatenated string: " << destination << "\n";
// Return 0 to indicate successful execution
return 0;
}
In this example, the strcat() function is used to concatenate the content of the source string to the end of the destination string
4. strncmp()
The strncmp() function in C++ is used to compare the first n characters of two strings. It is part of the
Example of strncmp() function:
#include <cstring>
// Main function
int main() {
char str1[] = "apple";
char str2[] = "apricot";
// Using strncmp to compare the first 3 characters of str1 and str2
int result = std::strncmp(str1, str2, 3);
if (result < 0) {
std::cout << "str1 is less than str2\n";
} else if (result > 0) {
std::cout << "str1 is greater than str2\n";
} else {
std::cout << "str1 is equal to str2\n";
}
return 0;
}
In this example, the strncmp() function is used to compare the first 3 characters of the strings str1 and str2. The result is then checked, and a message is printed based on the comparison.